import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
print(sys.path)

import json
from AppDB import AppDB
from AppStoreConnect import AppStoreConnectAPI
from io import StringIO
import pandas as pd


if __name__ == "__main__":

    date = '2023-10-02'

    asc = AppStoreConnectAPI(api_key_path="./AuthKey_sales_and_report_key_S6BQ948292.p8", api_issuer_id="69a6de81-f534-47e3-e053-5b8c7c11a4d1", api_key_id="S6BQ948292")

    sales_report = asc.get_sales_report(vendor_id='92612851', report_date=date)

    if sales_report is None:
        print("Failed to get sales report")
        exit(1)

    # Convert the sales report to a DataFrame
    df = pd.read_csv(StringIO(sales_report.read().decode('utf-8')), delimiter='\t')

    print('sales count:', len(df))

    data_list = df.to_dict('records')

    # Insert data into the table
    appDB = AppDB()

    appDB.add_summary_daily_report(date, data_list)

